<template>
    <div>
        <!-- 输入框 -->
        <div class="search">
           <div class="search_content">
               <div class="search_input">
                    <icon type='search' size='16'/>
                    <input @confirm='handleHistory' @input='handleInput' v-model='keyword' placeholder="请输入关键字" />
               </div>
               <button @click="cancelHandel" v-show="keyword">取消</button>  
               <div class="search_show">
                  <div v-for="item in searchData" :key="item.goods_id" class="search_item">{{item.goods_name}}</div>
               </div>
           </div>
        </div>
        <div class="searchHistory">
            <div class="history_title">
                <div>搜索历史</div>
                <icon @click='clearHandle' type='clear' size='16'/>
            </div>        
            <div class="history_content">
                <span class="history_show" v-for="(item,index) in historyKey" :key="index">
                    <navigator :url="'/pages/search_list/main?keyword=' + item">
                    {{item}}
                    </navigator>
                </span>
            </div>
            
        </div>
    </div>
</template>

<script>
import request from "../../utils/request";
export default {
    data(){
        return{
          searchData:[],
          keyword:'',
        //   控制搜索关键字发送请求的pinlv
          isLoading:false,
        //   定时器
        timer:null,
        // 定义历史关键字
        historyKey:wx.getStorageSync('history') || []
        }
    },
    methods:{
        //  清除缓存
        clearHandle(){
            wx.clearStorage();
            // 页面数据同步清空
            this.historyKey=[];
        },
        // 搜索历史相关操作
        handleHistory(){
            // 当keyword里面是空的时候不用储存
            if(!this.keyword){
                return;
            };
            // 按回车键的时候保存搜索的数据
           this.historyKey.unshift(this.keyword);
        //    进行数组中有重复数据操作
        this.historyKey = [...new Set(this.historyKey)];
        //    将获取的数据缓存到本地
        wx.setStorageSync('history',this.historyKey);
        // 搜索进行跳转
        mpvue.navigateTo({
        url: '/pages/search_list/main?keyword=' + this.keyword
      })
        },
        // 取消按钮操作,取消去掉input框中的内容
        cancelHandel(){
            this.keyword = '';
            this.handleInput();
        },
        handleInput(){
        //  这里做关键字请求发送频率的操作
        // if(this.isLoading){
        //     return ;
        // };
        // this.isLoading=true;
        clearTimeout(this.timer);
        this.timer = setTimeout(async ()=>{
             // 关键字搜索获取数据
            let {data:{message}} = await request('goods/qsearch',{query:this.keyword});
            this.searchData = message;
        },1000)
        // this.isLoading = false;
        }
    }
}
</script>

<style lang="less" scoped>
@import "./main.less";
</style>
